package com.sudworth.repository.network.okhttp;

import com.google.gson.Gson;
import com.google.gson.JsonIOException;
import com.google.gson.JsonSyntaxException;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonToken;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;

import okhttp3.ResponseBody;
import retrofit2.Converter;

public final class GsonResponseBodyConverter<T> implements Converter<ResponseBody, T> {
    private final Gson gson;
    private final TypeAdapter<T> adapter;

    GsonResponseBodyConverter(Gson gson, TypeAdapter<T> adapter) {
        this.gson = gson;
        this.adapter = adapter;
    }

    /**
     * 这么折腾的原因是 正确和错误返回的json格式不一致
     * {
     *     "message": "no power",
     *     "isError": true,
     *     "data": {}
     * }
     * @param value ResponseBody
     * @return
     * @throws IOException
     */
    @Override
    public T convert(ResponseBody value) throws IOException {
        String jsonStr = value.string();
        Reader reader = new StringReader(jsonStr);
        JsonReader jsonReader = gson.newJsonReader(reader);
        try {
            T result = adapter.read(jsonReader);
            if (jsonReader.peek() != JsonToken.END_DOCUMENT) {
                throw new JsonIOException("JSON document was not fully consumed.");
            }
            return result;
        } catch (JsonSyntaxException e) {
            try {
                JSONObject jsonObject = new JSONObject(jsonStr);
                if (jsonObject.has("data")) {
                    jsonObject.put("data", null);
                }
                String s = jsonObject.toString();
                Reader reader2 = new StringReader(s);
                JsonReader jsonReader2 = gson.newJsonReader(reader2);
                return adapter.read(jsonReader2);
            } catch (JSONException jsonException) {
                return adapter.read(jsonReader);
            }
        } finally {
            jsonReader.close();
        }
    }
}